<?php

namespace App\Kuafu\Mybank\Model;

use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\Shop\Model\Shop;
use App\Library\OperationLog\OperationLog;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\HasOne;

class MybankShopBindModel extends BaseModel
{
    use KfSoftDeletes;

    protected $table = "mybank_shop_bind";

    public static function getTranslateConfig(): array
    {
        return [
            "shopId" => [
                "type"   => OperationLog::FIELD_TABLE_COLUMN,
                "config" => [Shop::class, "id", "name"],
                "desc"   => "门店名称"
            ]
        ];
    }


    /**
     * @return HasOne
     */
    public function shopRel(): HasOne
    {
        return $this->hasOne(Shop::class, "id", "shopId");
    }

    /**
     * 通过shopId查询商户id
     * @param int $shopId
     * @return mixed
     */
    public static function getEntryIdByShopId(int $shopId)
    {
        return self::query()->where('shopId', $shopId)->value('entryId');
    }

    /**
     * 通过entryId查询商户shopId
     * @param int $entryId
     * @param array $entryIds
     * @return mixed
     */
    public static function getShopIdByEntryId(int $entryId = 0, array $entryIds = [])
    {
        return self::query()
                   ->when($entryIds, function ($query) use ($entryIds) {
                       $query->whereIn('entryId', $entryIds);
                   })
                   ->when($entryId, function ($query) use ($entryId) {
                       $query->where('entryId', $entryId);
                   })
                   ->pluck('shopId')->toArray();
    }

    /**
     * 通过id查询商户信息
     * @param int $id
     * @return mixed
     */
    public static function getEntryInfoId(int $id)
    {
        return self::query()->find($id);
    }


    /**
     * 通过shopId查询商户信息
     * @param array $shopIds
     * @return Builder[]|Collection
     */
    public static function getEntryByShopId(array $shopIds)
    {
        return self::query()
                   ->join('mybank_entry', 'mybank_shop_bind.entryId', '=', 'mybank_entry.id')
                   ->select([
                       'mybank_entry.merchantId',
                       'mybank_entry.merchantName',
                       'mybank_entry.id',
                       'mybank_shop_bind.shopId'
                   ])
                   ->whereIn('mybank_shop_bind.shopId', $shopIds)
                   ->where('mybank_entry.isDeleted', 0)
                   ->get();
    }
}
